package gold.gold01;

/**
 * 中等
 */
public class S0205链表求和 {
    /**
     * 100, 98 为何包括每次创建新node的在内, 所有人都是100.
     * 直接移一位, *10一次, 搞定。返回的是ListNode, 甚至不用*10。
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1 == null || l2 == null) return l1 == null? l2 : l1;
        // 此时两个链表的表头起码都不为空
        ListNode result = l1;
        int carryPre = 0;
        int carryCur = 0;
        while (true){
            carryCur = (l1.val + l2.val + carryPre) / 10;
            l1.val = (l1.val + l2.val + carryPre) % 10;
            if(l1 .next == null){
                if(carryCur == 0){
                    l1.next = l2.next;
                }else{
                    l1.next = addTwoNumbers(new ListNode(1), l2.next);
                }
                return result;
            }else if(l2.next == null){
                if(carryCur == 1)
                    l1.next = addTwoNumbers(new ListNode(1), l1.next);
                return result;
            }else{
                l1 = l1.next;
                l2 = l2.next;
                carryPre = carryCur;
            }
        }
    }
}
